package com.nwpu.coursesupport.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nwpu.coursesupport.entity.*;
import com.nwpu.coursesupport.entity.Class;
import com.nwpu.coursesupport.entity.bean.JSONResult;
import com.nwpu.coursesupport.entity.bean.Response;
import com.nwpu.coursesupport.service.ClassService;
import com.nwpu.coursesupport.service.ClassStudentService;
import com.nwpu.coursesupport.service.TaskAssignmentService;
import com.nwpu.coursesupport.service.TaskSubmitResultService;
import com.nwpu.coursesupport.service.imple.*;
import com.nwpu.coursesupport.service.param.IDParam;
import com.nwpu.coursesupport.tool.JSONUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import com.nwpu.coursesupport.service.imple.TaskService;

import java.util.ArrayList;
import java.util.List;
import java.lang.Math;

//import static jdk.nashorn.internal.objects.NativeFunction.function;

@Controller
public class VisualizationController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private TaskAssignmentService taskAssignmentService;
    @Autowired
    private TaskSubmitResultService taskSubmitResultService;

    @Autowired
    private CourseTargetService courseTargetService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private ClassService classService;

    @Autowired
    private ClassStudentService classStudentService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TaskCourseTargetService taskCourseTargetService;

    @Data
    @AllArgsConstructor
    private class PieChart{
        Double value;
        String name;

        @Override
        public String toString() {
            return "{value:" + value + ", name:'" + name + "\'" + '}';
        }
    }

    @Data
    @AllArgsConstructor
    private class ClassData{
        Integer classID;
        String className;
        Double avg;
        Double top;
        Double low;
        Double mid;
        Double std;
    }

    @Data
    @AllArgsConstructor
    private class StuData{
        Integer stuID;
        String stuName;
        Double score;
    }

    @Data
    @AllArgsConstructor
    private class ClassStuData{
        String className;
        List<StuData> stuData;
    }

    @RequestMapping(value="/visualize",method= RequestMethod.GET)
    @ResponseBody
    public Object visualize(Integer courseID, Integer stuID) {

        JSONObject rst = new JSONObject();

        //学生姓名
        Student student = studentService.findById(stuID);
        String stuName = student.getName();

        //1.查课目标
        List<CourseTarget> courseTargets = courseTargetService.courseTargetsByCourseId(courseID);
        List<String> courseTargetNames = new ArrayList<>();
        List<String> courseTargetNamesAddQuota = new ArrayList<>();
        for (CourseTarget courseTarget : courseTargets) {
            courseTargetNames.add(courseTarget.getDescription());
            courseTargetNamesAddQuota.add("\"" + courseTarget.getDescription() + "\"");
        }

        //2.sum(得分*权重)/sum(满分*权重)

        List<Double> control = new ArrayList<>();
        List<Double> taskTargetWeight = new ArrayList<>();
        List<PieChart> chart = new ArrayList<>();
        for (CourseTarget courseTarget : courseTargets) {
            Double numerator = 0.0;//分子
            Double denominator = 0.0;//分母
            Double fullMarkSum = 0.0;
            //有成绩的任务
            List<TaskSubmitResult> taskSubmitResultById = taskSubmitResultService.findTaskSubmitResultById(stuID);
            for (TaskSubmitResult taskSubmitResult : taskSubmitResultById) {
                //满分
                System.out.println("taskSubmitResult.getAssignId()"+taskSubmitResult.getAssignId());
                Integer taskId = taskAssignmentService.findTaskId(taskSubmitResult.getAssignId());
                System.out.println("TaskID"+taskId);
                Task task = (Task) taskService.getTaskById(taskId).getData();
                if( courseID.compareTo(task.getCourseId() ) != 0) continue;
                //权重
                Double weight = taskCourseTargetService.getWeight(courseTarget.getId(), task.getId());

                //task满分之和
                fullMarkSum += task.getFullMark();
                System.out.println("taskSubmitResult.getScore()"+taskSubmitResult.getScore());
                numerator += taskSubmitResult.getScore() * weight;

                denominator += task.getFullMark() * weight;
            }
            if(Math.abs(denominator)<1e-6) {
                control.add(0.0);
            } else{
                control.add(numerator / denominator);
            }
            //掌握情况
            System.out.println("==================================="+numerator +"=================================="+ denominator);
            System.out.println("==================================="+denominator +"=================================="+ fullMarkSum);
            //3.sum(满分*权重)/sum(满分)
            taskTargetWeight.add(denominator / fullMarkSum);
        }

        for (int i = 0; i < courseTargetNames.size(); i++) {
            chart.add(new PieChart(taskTargetWeight.get(i), courseTargetNames.get(i)));
        }

        //pie处理
        String pieResult = "[";
        for (int i = 0; i < chart.size(); i++) {
            if(i > 0) pieResult += ',';
            pieResult += chart.get(i).toString();
        }
        pieResult += ']';

        rst.put("targetControl",control);
        rst.put("targetNames",courseTargetNames);
        rst.put("pieChart",chart);
        rst.put("stuName",stuName);
        System.out.println(rst);
        //modelAndView.setViewName("/common/scoreCharts");
        return rst;
    }

    @RequestMapping(value="/avgScore",method= RequestMethod.GET)
    @ResponseBody
    public Object avgScore(String className){
        JSONObject rst = new JSONObject();

        //存储
        List<PieChart> chart = new ArrayList<>();

        //1,查分配记录的id
        List<Integer> assignmentIDs = taskAssignmentService.findAssignmentIDByClassName(className);

        List<Double> allAvgScores = new ArrayList<>();
        List<Double> allAnsNums = new ArrayList<>();
        List<String> allTaskNames = new ArrayList<>();
        //2,算平均数
        for (Integer assignmentID : assignmentIDs) {
            Integer taskID = taskAssignmentService.findTaskId(assignmentID);
            Response task = taskService.getTaskById(taskID);
            Task data = (Task)task.getData();
            String name = data.getTitle();
            Double sum = taskSubmitResultService.findSumScoreByAssignID(new ArrayList<>(assignmentID));
            Double num = taskSubmitResultService.findAnsNumByAssignID(new ArrayList<>(assignmentID));
            System.out.println("findSumScoreByAssignID:   "+sum);
            System.out.println("findAnsNumByAssignID:     "+num);
            allAvgScores.add(sum/num);
            allAnsNums.add(num);
            allTaskNames.add(name);
        }



//        modelAndView.addObject("allAvgScores",allAvgScores.toString());
//        modelAndView.addObject("allAnsNums",allAnsNums.toString());
//        modelAndView.addObject("allTaskNames",allTaskNames.toString());
//        modelAndView.setViewName("/teapage/common/AvgScore");

        rst.put("allAvgScores",allAvgScores);
        rst.put("allAnsNums",allAnsNums);
        rst.put("allTaskNames",allTaskNames);

        return rst;
    }

    @RequestMapping(value="/courseTaskAnalysis",method= RequestMethod.GET)
    public ModelAndView CourseTaskAnalysis(@RequestParam("courseID")Integer courseID, @RequestParam("taskID")Integer taskID) throws Exception {
        System.out.println("sssssss");
        System.out.println("CCCCOURSEID"+courseID);
        System.out.println("TTTTaskID"+taskID);
        //查课程和任务的基本信息
        Response r1 = taskService.getTaskById(taskID);
        Response r2 = courseService.getCourseByID(courseID);
        Course course = (Course)r2.getData();
        String courseName = course.getName();
        //根据taskID查task_assignment中task分配到的classNames
        List<String> classNames = taskAssignmentService.findClassNamesBytaskID(taskID);

        //1，算每个班的数据
        List<ClassData> classDatas = new ArrayList<>();

        //根据className和taskID查assignmentID，然后根据assignmentID查平均分等数据
        for (int i = 0; i < classNames.size(); i++) {
            Integer id = classService.getClassIDByClassName(classNames.get(i));
            Integer assignmentID = taskAssignmentService.findAssignmentIDByClassNameandTaskID(classNames.get(i), taskID);
            System.out.println("QQQQQQQQQQQQQQQ"+assignmentID);
            Double sum = taskSubmitResultService.findSumScoreByAssignID(new ArrayList<Integer>(){{add(assignmentID);}});
            Double num = taskSubmitResultService.findAnsNumByAssignID(new ArrayList<Integer>(){{add(assignmentID);}});
            Double top = taskSubmitResultService.findTopScoreByAssignID(new ArrayList<Integer>(){{add(assignmentID);}});
            Double low = taskSubmitResultService.findLowScoreByAssignID(new ArrayList<Integer>(){{add(assignmentID);}});
            Double mid = taskSubmitResultService.findMidScoreByAssignID(new ArrayList<Integer>(){{add(assignmentID);}});
            Double std = taskSubmitResultService.findStdScoreByAssignID(new ArrayList<Integer>(){{add(assignmentID);}});
            System.out.println(classNames.get(i) + "findSumScoreByAssignID:   "+sum);
            System.out.println(classNames.get(i) + "findAnsNumByAssignID:     "+num);
            System.out.println(classNames.get(i) + "findTopScoreByAssignID:     "+top);
            System.out.println(classNames.get(i) + "findLowScoreByAssignID:     "+low);
            System.out.println(classNames.get(i) + "findMidScoreByAssignID:     "+mid);
            System.out.println(classNames.get(i) + "findStdScoreByAssignID:     "+std);
            classDatas.add(new ClassData(id,classNames.get(i),sum/num, top, low, mid, std));
        }

        //Double courseTop = Math.max.apply(Math, classDatas.map(function(o) {return o.top}));
        //2.算课程总的数据
        List<Integer> assignmentIDs = taskAssignmentService.findAssignmentIDByTaskID(taskID);
        Double courseSum = taskSubmitResultService.findSumScoreByAssignID(assignmentIDs);
        Double courseNum = taskSubmitResultService.findAnsNumByAssignID(assignmentIDs);
        Double courseTop = taskSubmitResultService.findTopScoreByAssignID(assignmentIDs);
        Double courseLow = taskSubmitResultService.findLowScoreByAssignID(assignmentIDs);
        Double courseMid = taskSubmitResultService.findMidScoreByAssignID(assignmentIDs);
        Double courseStd = taskSubmitResultService.findStdScoreByAssignID(assignmentIDs);

        System.out.println("findSumScoreByAssignID:   "+courseSum);
        System.out.println("findAnsNumByAssignID:     "+courseNum);
        System.out.println("findTopScoreByAssignID:     "+courseTop);
        System.out.println("findLowScoreByAssignID:     "+courseLow);
        System.out.println( "findMidScoreByAssignID:     "+courseMid);
        System.out.println( "findStdScoreByAssignID:     "+courseStd);

        List<StuData> allStuDatas = new ArrayList<>();
        List<Double> allStuScore = taskSubmitResultService.findAllStuScore(assignmentIDs);
        List<String> allStuName = taskSubmitResultService.findAllStuName(assignmentIDs);
        List<Integer> allStuID = taskSubmitResultService.findAllStuID(assignmentIDs);

        //先找assignment表中的lessonid,
        for (int i = 0; i < allStuID.size(); i++) {
            allStuDatas.add(new StuData(allStuID.get(i),allStuName.get(i), allStuScore.get(i)));
        }

        List<ClassStuData> classStuDatas = new ArrayList<>();
        for (int i = 0; i < classNames.size(); i++) {
            //查这个班这个任务的assignmentID，即可查这个班所有提交记录
            Integer tmpAssignmentID = taskAssignmentService.findAssignmentIDByClassNameandTaskID(classNames.get(i), taskID);
            List<Double> tmpStuScore = taskSubmitResultService.findAllStuScore(new ArrayList<Integer>(){{add(tmpAssignmentID);}});
            List<String> tmpStuName = taskSubmitResultService.findAllStuName(new ArrayList<Integer>(){{add(tmpAssignmentID);}});
            List<Integer> tmpStuID = taskSubmitResultService.findAllStuID(new ArrayList<Integer>(){{add(tmpAssignmentID);}});
            List<StuData> tmpStuDatas = new ArrayList<>();
            for (int j = 0; j < tmpStuID.size(); j++) {
                tmpStuDatas.add(new StuData(tmpStuID.get(j),tmpStuName.get(j), tmpStuScore.get(j)));
            }
            classStuDatas.add(new ClassStuData(classNames.get(i),tmpStuDatas));
        }
        IDParam idParam = new IDParam();
        idParam.setId(taskID);
        JSONObject taskData = JSON.parseObject(JSONUtils.obj2json(taskService.detail(idParam)));
//        JSONResult taskData = taskService.detail(idParam);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("data", taskData);
        modelAndView.addObject("courseName", courseName);
        modelAndView.addObject("allStuNum", allStuID.size());
        modelAndView.addObject("courseAvg", courseSum/courseNum);
        modelAndView.addObject("courseTop", courseTop);
        modelAndView.addObject("courseLow", courseLow);
        modelAndView.addObject("courseMid", courseMid);
        modelAndView.addObject("courseStd", courseStd);
        modelAndView.addObject("classDatas", JSON.toJSON(classDatas));
        modelAndView.addObject("allStuDatas", JSON.toJSON(allStuDatas));
        modelAndView.addObject("classStuDatas", JSON.toJSON(classStuDatas));
        modelAndView.setViewName("/teapage/courseTaskAnalysis");

        return modelAndView;
    }
}
